package com.cyan.app.workflow.activity.Common;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cyan.app.workflow.AppData;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.ProssBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.PullDownView;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by owen on 2019-09-05.
 */
public class WorkProcedureActivity extends BaseActivity implements PullDownView.OnPullDownListener, AdapterView.OnItemClickListener
{
    public static final String TAG = "WorkProcedureActivity";
    private List<ProssBean.WorkProcudure> mProssBeans;
    private SalaryAdapter adapter;
    private ListView prossinfo_lv;
    private PullDownView mPullDownView;
    private Boolean isPressMore = false;
    private int pageCount = 15;
    private Context context = null;
    /** 请求第几页数据 */
    private int intPageNo = 1;
    /** 是否有下一页 */
    private boolean nextPage = false;
    private ShowTipDialog showdialog = new ShowTipDialog();
    private List<ProssBean.WorkProcudure> mProssDatas = new ArrayList<ProssBean.WorkProcudure>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.workprocedurelist);
        titleBar();
        mPullDownView = (PullDownView) findViewById(R.id.prossinfo_lv);
        mPullDownView.setOnPullDownListener(this);
        prossinfo_lv = mPullDownView.getListView();
        prossinfo_lv.setOnItemClickListener(this);
        // 隐藏并且禁用头部刷新
        mPullDownView.setHideHeader();
        AsyncLoader task = new AsyncLoader();
        task.execute();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
    public class AsyncLoader extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            showdialog.showDialog(WorkProcedureActivity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try{
                JSONObject param = new JSONObject();
                param.put("FactoryID", HttpConfig.Main_FactoryID);
                param.put("UserNo", AppData.getInstance().getUserId());
                param.put("Connectstring", AppData.getInstance().getConnectstring());
                result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, "GetPross", param.toString(), getApplicationContext());
            }catch (Exception e){
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null) {
                showdialog.closeDialog();
                return;
            }
            ProssBean prossBean = new Gson().fromJson(s, ProssBean.class);
            mProssBeans = prossBean.getResult();
            startProssThread();
            showdialog.closeDialog();
        }
    }
    private void getData(int PageNo){
        if(mProssBeans==null) return;
        int count = (intPageNo*pageCount)> mProssBeans.size()?mProssBeans.size():intPageNo*pageCount;
        for(int i = (intPageNo-1)* pageCount;i< count;i++){
            mProssDatas.add(mProssBeans.get(i));
        }
    }
    private void  showList(){
        // 获取更多数据之外的请求，如首次请求数据，
        if (!isPressMore) {
            getData(intPageNo);
            adapter = new SalaryAdapter(WorkProcedureActivity.this);
            prossinfo_lv.setAdapter(adapter);
        }else {
            // 获取更多数据
            getData(intPageNo);
            adapter.notifyDataSetChanged();
        }
        // 判断是否有下一页
        if (mProssBeans.size() > mProssDatas.size()) {
            // 显示并启用自动获取更多
            mPullDownView.setShowFooter();
            // 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
            mPullDownView.enableAutoFetchMore(true, 1);
        } else {
            // 隐藏 并禁用尾部
            mPullDownView.setHideFooter();
            // 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
            mPullDownView.enableAutoFetchMore(false, 1);
        }
        // 告诉它获取更多完毕 这个事线程安全的 可看源代码
        mPullDownView.notifyDidMore();

        isPressMore = false;
    }
    private void titleBar() {
        TextView mTitleName = (TextView) findViewById(R.id.top_title_info);
        mTitleName.setText("工序选择");
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
    }
    /**
     * listview单项点击事件
     */
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = WorkProcedureActivity.this.getIntent();
        //Bundle bundle=new Bundle();
        //bundle.putString("prosscode",mProssDatas.get(position).getProsscode());
        intent.putExtra("prosscode", mProssDatas.get(position).getProcedureNo());
        WorkProcedureActivity.this.setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * listview刷新
     */
    public void onRefresh() {

    }
    /**
     * listview更多
     */
    public void onMore() {
        isPressMore = true;
        // 发送更多请求
        intPageNo++;
        startProssThread();
    }
    // 启动线程
    private void startProssThread() {
        showList();
    }
    public class SalaryAdapter extends BaseAdapter {
        private LayoutInflater inflater = null;
        public SalaryAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mProssDatas.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            holder = new ViewHolder();
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = Gravity.CENTER_VERTICAL;
            convertView = inflater.inflate(R.layout.sfc_gdlz_gx_list, null);
            holder.sfc_pross_list_name = (TextView) convertView.findViewById(R.id.sfc_pross_list_name);
            holder.sfc_pross_list_code = (TextView) convertView.findViewById(R.id.sfc_pross_list_code);
            holder.sfc_pross_list_selected = (CheckBox) convertView.findViewById(R.id.sfc_pross_list_selected);
            holder.sfc_pross_list_name.setText(mProssDatas.get(position).getProcedureName());
            holder.sfc_pross_list_code.setText(mProssDatas.get(position).getProcedureNo());
            holder.sfc_pross_list_selected.setChecked(false);

            holder.sfc_pross_list_selected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        Intent intent = WorkProcedureActivity.this.getIntent();
                        //Bundle bundle=new Bundle();
                        //bundle.putString("prosscode",mProssDatas.get(position).getProsscode());
                        intent.putExtra("prosscode", mProssDatas.get(position).getProcedureNo());
                        WorkProcedureActivity.this.setResult(RESULT_OK, intent);
                        WorkProcedureActivity.this.finish();
                        //onKeyDown(KeyEvent.KEYCODE_BACK, null);
                        //System.exit(0);
                    }
                }
            });

            convertView.setTag(holder);

            return convertView;
        }

        class ViewHolder {
            TextView sfc_pross_list_code;
            TextView sfc_pross_list_name;
            CheckBox sfc_pross_list_selected;
        }
    }
}
